#!/bin/bash

# --------------------------
# Configuration & Usage
# --------------------------
usage() {
    echo "Usage: $0 [sdl|x11]"
    echo "  Builds self-contained Debian packages with embedded stest:"
    echo "  - $0 sdl  : Builds sdlmenu.deb (with sdlmenu_path + sdlmenu_run + stest)"
    echo "  - $0 x11  : Builds xmenu.deb (with xmenu_path + xmenu_run + stest)"
    exit 1
}

# Common config
PKG_VERSION="0.99"
PKG_ARCH="amd64"
MAINTAINER="etcix<1690544550@qq.com>"
SRC_DIR="$(pwd)"
TMP_SCRIPTS_DIR="${SRC_DIR}/tmp_scripts"
STEST_SRC="${SRC_DIR}/stest.c"  # Path to your local stest.c


# --------------------------
# Generate Helper Scripts
# --------------------------
generate_helpers() {
    local prefix=$1
    mkdir -p "${TMP_SCRIPTS_DIR}"

    # Generate ${prefix}_path
    cat > "${TMP_SCRIPTS_DIR}/${prefix}_path" << EOF
#!/bin/sh
# Auto-generated - ${prefix} path cache (uses embedded stest)
cachedir="\${XDG_CACHE_HOME:-"\$HOME/.cache"}"
cache="\${cachedir}/${prefix}_run"

[ ! -e "\$cachedir" ] && mkdir -p "\$cachedir"

IFS=:
# Use bundled stest (no system dependency)
if stest -dqr -n "\$cache" \$PATH; then
    stest -flx \$PATH | sort -u | tee "\$cache"
else
    cat "\$cache"
fi
EOF

    # Generate ${prefix}_run
    cat > "${TMP_SCRIPTS_DIR}/${prefix}_run" << EOF
#!/bin/sh
# Auto-generated - ${prefix} launcher
${prefix}_path | ${prefix} "\$@" | \${SHELL:-"/bin/sh"} &
EOF

    chmod 755 "${TMP_SCRIPTS_DIR}/${prefix}_path" "${TMP_SCRIPTS_DIR}/${prefix}_run"
}


# --------------------------
# Main Build Logic
# --------------------------
if [ $# -ne 1 ] || [[ ! "$1" =~ ^(sdl|x11)$ ]]; then
    usage
fi

# Package-specific config
if [ "$1" = "sdl" ]; then
    PKG_NAME="sdlmenu"
    SRC_FILE="sdlmenu.c"
    PKG_DESCRIPTION="SDL3-based menu launcher (self-contained)
 Includes ${PKG_NAME}_path, ${PKG_NAME}_run, and embedded stest (no external dependencies).
 Uses static SDL3."
    DEPENDS="libc6 (>= 2.28), libfreetype6"  # Removed stest dependency
    LOCAL_LIB_DIR="${SRC_DIR}/lib"
    LOCAL_INCLUDE_DIR="${SRC_DIR}/include"
    COMPILE_FLAGS="-I ${LOCAL_INCLUDE_DIR} \
                   -L ${LOCAL_LIB_DIR} \
                   -l:libSDL3.a \
                   -lm -lpthread -ldl -lrt -lX11"

elif [ "$1" = "x11" ]; then
    PKG_NAME="xmenu"
    SRC_FILE="xmenu.c"
    PKG_DESCRIPTION="X11-based popup menu launcher (self-contained)
 Includes ${PKG_NAME}_path, ${PKG_NAME}_run, and embedded stest (no external dependencies).
 Lightweight X11 menu."
    DEPENDS="libc6 (>= 2.28), libx11-6, libxft2, libfreetype6"
    COMPILE_FLAGS="$(pkg-config --cflags --libs x11 xft) -I/usr/include/freetype2 -lm -Wno-deprecated-declarations"
fi

# Derived paths
BUILD_DIR="${SRC_DIR}/${PKG_NAME}_deb_build"
DEB_DEST="${SRC_DIR}/${PKG_NAME}_${PKG_VERSION}_${PKG_ARCH}.deb"
BIN_DEST="${BUILD_DIR}/usr/local/bin"


# --------------------------
# Step 1: Check Dependencies
# --------------------------
echo "=== Checking dependencies ==="

# Core tools
if ! command -v gcc &> /dev/null; then
    echo "ERROR: gcc not installed. Install with: sudo apt install gcc"
    exit 1
fi
if ! command -v dpkg-deb &> /dev/null; then
    echo "ERROR: dpkg-deb not installed. Install with: sudo apt install dpkg-dev"
    exit 1
fi

# Check local stest.c exists
if [ ! -f "${STEST_SRC}" ]; then
    echo "ERROR: Missing stest.c at ${STEST_SRC} (required for path caching)"
    exit 1
fi

# Package-specific checks
if [ "$1" = "sdl" ]; then
    if [ ! -d "${LOCAL_INCLUDE_DIR}" ] || [ ! -f "${LOCAL_LIB_DIR}/libSDL3.a" ]; then
        echo "ERROR: Missing SDL3 static files. Ensure ${LOCAL_LIB_DIR}/libSDL3.a and ${LOCAL_INCLUDE_DIR} exist."
        exit 1
    fi
elif [ "$1" = "x11" ]; then
    if ! pkg-config --exists x11 xft; then
        echo "ERROR: X11 dependencies missing. Install with: sudo apt install libx11-dev libxft-dev"
        exit 1
    fi
fi

# Check main source file
if [ ! -f "${SRC_DIR}/${SRC_FILE}" ]; then
    echo "ERROR: Missing source file: ${SRC_DIR}/${SRC_FILE}"
    exit 1
fi


# --------------------------
# Step 2: Generate Helpers & Compile stest
# --------------------------
echo -e "\n=== Generating helpers and compiling stest ==="
generate_helpers "${PKG_NAME}"

# Compile local stest.c (embedded in package)
echo -e "\n=== Compiling stest from local stest.c ==="
gcc -o "${TMP_SCRIPTS_DIR}/stest" "${STEST_SRC}" -O2  # Optimized build


# --------------------------
# Step 3: Clean Previous Build
# --------------------------
echo -e "\n=== Cleaning previous build ==="
rm -rf "${BUILD_DIR}" "${DEB_DEST}"


# --------------------------
# Step 4: Create Debian Structure
# --------------------------
echo -e "\n=== Creating package structure ==="
mkdir -p "${BIN_DEST}"
mkdir -p "${BUILD_DIR}/DEBIAN"

# Control file (no stest dependency)
cat > "${BUILD_DIR}/DEBIAN/control" << EOF
Package: ${PKG_NAME}
Version: ${PKG_VERSION}
Section: utils
Priority: optional
Architecture: ${PKG_ARCH}
Maintainer: ${MAINTAINER}
Depends: ${DEPENDS}
Description: ${PKG_DESCRIPTION}
EOF

chmod 755 "${BUILD_DIR}/DEBIAN"


# --------------------------
# Step 5: Compile Main Binary & Install All Files
# --------------------------
echo -e "\n=== Compiling ${PKG_NAME} ==="
gcc -o "${BIN_DEST}/${PKG_NAME}" \
    "${SRC_DIR}/${SRC_FILE}" \
    ${COMPILE_FLAGS} \
    $(pkg-config --cflags --libs freetype2)

echo -e "\n=== Installing all components ==="
# Install helpers
cp "${TMP_SCRIPTS_DIR}/${PKG_NAME}_path" "${BIN_DEST}/"
cp "${TMP_SCRIPTS_DIR}/${PKG_NAME}_run" "${BIN_DEST}/"
# Install embedded stest
cp "${TMP_SCRIPTS_DIR}/stest" "${BIN_DEST}/"


# --------------------------
# Step 6: Verify Package Contents
# --------------------------
echo -e "\n=== Verifying package contents ==="
for file in "${PKG_NAME}" "${PKG_NAME}_path" "${PKG_NAME}_run" "stest"; do
    if [ ! -x "${BIN_DEST}/${file}" ]; then
        echo "ERROR: Missing or non-executable file: ${file}"
        exit 1
    fi
    echo "✓ Verified: ${file}"
done


# --------------------------
# Step 7: Build DEB Package
# --------------------------
echo -e "\n=== Building ${DEB_DEST} ==="
dpkg-deb --build --root-owner-group "${BUILD_DIR}" "${DEB_DEST}"


# --------------------------
# Step 8: Cleanup
# --------------------------
echo -e "\n=== Cleaning up ==="
rm -rf "${BUILD_DIR}" "${TMP_SCRIPTS_DIR}"

echo -e "\n=== Build Complete! ==="
echo "Install with: sudo dpkg -i ${DEB_DEST}"
echo "Launch with: ${PKG_NAME}_run"
